import 'dart:async';

import 'package:after_sale_plugin/package_bridge.dart';
import 'package:after_sale_plugin/pages/models/order_model.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/http/api_helper_after_sale.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mine/user_info/mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/http_request_mixin.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/pages/models/settting_item_model.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/service/realtime_data_server/realtime_data_polling_timer_helper.dart';
import '../../service/realtime_data_server/realtime_data_service.dart';
import '../mixin/vehicle_type_mixin.dart';
import 'after_plugin_helper.dart';
import 'state.dart';

// "我的"控制器
class MineController extends GetxController
    with
        UserBasicInformationMixin,
        CacheMixin,
        HttpRequestMixin,
        RealtimeInfoMixin {
  // 状态
  final MineState state = MineState();

  // 首页页面需要轮询的实时数据类型列表
  List<(PollingTimerType, int)> get _vehicleHomePagePollingTypes =>
      RealtimeDataPollingTimeHelper.vehicleHomePagePollingTypes;

  // 当前车辆类型
  VehicleType get _vehicleType => GlobalService.to.currentVehicleType;

  @override
  void onInit() {
    super.onInit();

    // 功能列表
    state.itemList.value = _vehicleType.minePageCellList();

    // 赋值OnTap事件
    for (int i = 0; i < state.itemList.length; i++) {
      for (int j = 0; j < state.itemList[i].subItems.length; j++) {
        _setCellOnTap(state.itemList[i].subItems[j]);
      }
    }

    // 重新加载数据
    reloadPageData();
  }

  // 编辑用户信息
  editUserInfoOnTap() {
    realtimeInfoMixinNavigatorToNamed(AppRoutes.USER_INFO,
        pollingTypes: _vehicleHomePagePollingTypes);
  }

  // 车辆列表点击事件
  vehicleListOnTap() {
    realtimeInfoMixinNavigatorToNamed(AppRoutes.VEHICLE_LIST,
        pollingTypes: _vehicleHomePagePollingTypes);
  }

  // 设置页面cell点击事件
  _setCellOnTap(SettingRowModel model) async {
    if (model.title == local.ticket_service) {
      // 工单服务
      model.onTap = () {
        AfterPluginHelper.toNamedPlugin(
            AfterSalePluginRouteEnum.clickForService,
            onRefreshWorkerTicketCallback: () {
          _getLatestAfterSaleOrderInfo();
        });
      };
    } else if (model.title == local.ticket_history) {
      // 工单历史
      model.onTap = () {
        AfterPluginHelper.toNamedPlugin(AfterSalePluginRouteEnum.orderHistory,
            onRefreshWorkerTicketCallback: () {
          _getLatestAfterSaleOrderInfo();
        });
      };
    } else if (model.title == local.online_customer_service) {
      // 在线客服
    } else if (model.title == local.product_manual) {
      // 产品手册
      model.onTap = () {
        AfterPluginHelper.toNamedPlugin(AfterSalePluginRouteEnum.productManual);
      };
    } else if (model.title == local.video_guide) {
      // 视频指南
      model.onTap = () {
        AfterPluginHelper.toNamedPlugin(AfterSalePluginRouteEnum.vehicleGuide);
      };
    } else if (model.title == local.settings) {
      // 设置
      model.onTap = () {
        realtimeInfoMixinNavigatorToNamed(AppRoutes.MINE_SETTING,
            pollingTypes: _vehicleHomePagePollingTypes);
      };
    }
  }

  // 工单详情
  viewOrderDetailOnTap(String orderId) {
    AfterPluginHelper.toNamedPlugin(AfterSalePluginRouteEnum.orderDetail,
        orderNumber: orderId, onRefreshWorkerTicketCallback: () {
      _getLatestAfterSaleOrderInfo();
    });
  }

  // 页面可见时重新加载数据
  reloadPageData() {
    if (!GlobalService.to.isLoggedIn) return;
    state.userInfo.value = GlobalService.to.cacheUserInfo.value;
    GlobalService.to.cacheUserInfo.listen((p0) {
      state.userInfo.value = p0;
    });
    Future.wait([
      // 获取用户信息
      _getUserInfo(),
      // 获取售后最近一条工单信息
      _getLatestAfterSaleOrderInfo(),
    ]).catchErrorHandler();
  }

  // 获取用户信息
  Future<bool> _getUserInfo() {
    if (!GlobalService.to.isLoggedIn) return Future.value(false);
    return ApiHelper().getUserInfo().then((model) async {
      state.userInfo.value = model;
      return cacheMixinUpdateUser(
        model.uid,
        avatar: model.avatar,
        nickName: model.nickname,
        signature: model.signature,
        phone: model.phone,
        email: model.email,
      );
    });
  }

  // 获取售后最近一条工单信息
  Future<void> _getLatestAfterSaleOrderInfo() {
    if (!GlobalService.to.isLoggedIn) return Future.value();
    return ApiHelper().getWorkOrderList().then((rsp) {
      if (rsp["data"] == null) {
        return Future.value();
      }
      List<ReportOrderInfo> list = (rsp["data"] as List<dynamic>)
          .map((e) => ReportOrderInfo.fromMap(e as Map<String, dynamic>))
          .toList();
      if (list.isNotEmpty) {
        state.latestOrderInfo.value = list.first;
      }
      return Future.value();
    });
  }
}
